#include "adxl345.h"
#include "i2c.h"
#include "uart.h"

/* Accelerometer i2c device */
i2c_device_t adxl345 =
{ XL345_I2C_ADDRESS };

/**
 * Initialize accelerometer
 *
 * @param void
 * @return void
 *
 * @brief  init accelerometer sensor
 */
void adxl345_init(void)
{
	uint8_t data;

	/* Go into standby mode to configure the device. */
	data = XL345_WAKEUP_8HZ;
	adxl345_write_reg(XL345_POWER_CTL, &data);

	/* Full resolution, 4mg/LSB. */
	data = XL345_RANGE_16G;
	adxl345_write_reg(XL345_DATA_FORMAT, &data);

	/* 400Hz data rate. */
	data = XL345_RATE_1600;
	adxl345_write_reg(XL345_BW_RATE, &data);

	/* Measurement mode. */
	data = XL345_MEASURE;
	adxl345_write_reg(XL345_POWER_CTL, &data);

}

/**
 * Read Accelerometer Device ID
 *
 * @param uint8_t* id Device ID
 * @return uint32_t i2c read status
 *
 * @brief  init accelerometer sensor
 */
uint32_t adxl345_read_id(uint8_t* id)
{
	return adxl345_read_reg(XL345_DEVID, id);
}

/**
 * Read Accelerometer X Y Z values
 *
 * @param int16_t *readings accel values
 * @return uint32_t i2c read status
 *
 * @brief  read acceleration values
 */
uint32_t adxl345_read_xyz(int16_t *readings)
{
	uint8_t value[6];
	uint32_t ret;

	/* It is recommended that a multiple-byte
	read of all registers be performed to prevent a change in data
	between reads of sequential registers. */
	ret = i2c_read_burst(&adxl345, XL345_DATAX0, value);

	/* convert values */
	readings[0] = ((value[1] << 8) | value[0]);
	readings[1] = ((value[3] << 8) | value[2]);
	readings[2] = ((value[5] << 8) | value[4]);
	return ret;
}

/**
 * Read Accelerometer register
 *
 * @param uint8_t reg device register address
 * @param uint8_t *data
 * @return uint32_t i2c read status
 *
 * @brief  read acc register value
 */
uint32_t adxl345_read_reg(uint8_t reg, uint8_t *data)
{
	return i2c_read(&adxl345, reg, data);
}

/**
 * Write Accelerometer register
 *
 * @param uint8_t reg device register address
 * @param uint8_t *data
 * @return i2c write status
 *
 * @brief  get acc register value
 */
uint32_t adxl345_write_reg(uint8_t reg, uint8_t *data)
{
	return i2c_write(&adxl345, reg, data);
}

